package com.woniuxy.project115.kaer.tenant.service.impl;

import com.woniuxy.project115.kaer.tenant.entity.ServiceType;
import com.woniuxy.project115.kaer.tenant.mapper.ServiceTypeMapper;
import com.woniuxy.project115.kaer.tenant.service.ServiceTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.project115.kaer.tenant.util.RedisKey;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author HuH
 * @since 2025年02月17日
 */
@Service
public class ServiceTypeServiceImpl extends ServiceImpl<ServiceTypeMapper, ServiceType> implements ServiceTypeService {
    @Resource
    private ServiceTypeMapper serviceTypeMapper;

    @Resource
    private RedisTemplate<String, Object> redisObjectTemplate;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public List<ServiceType> getServiceType() throws Exception {
        //先查看redis缓存中是否有数据
        if (redisObjectTemplate.hasKey(RedisKey.CACHE_TYPE_TREE())) {
            return (List<ServiceType>) redisObjectTemplate.opsForValue().get(RedisKey.CACHE_TYPE_TREE());
        }
        //如果过期时间小于30分钟，则更新缓存
        if (redisObjectTemplate.getExpire(RedisKey.CACHE_TYPE_TREE(), TimeUnit.SECONDS) < 30) {
            CorrelationData messageId = new CorrelationData(UUID.randomUUID().toString());
            rabbitTemplate.convertAndSend("", "update_cache_queue", RedisKey.CACHE_TYPE_TREE(), messageId);
        }

        //查询所有服务类型
        List<ServiceType> serviceTypeList = serviceTypeMapper.selectList(null);

        //将数据存入redis缓存中
        redisObjectTemplate.opsForValue().set(RedisKey.CACHE_TYPE_TREE(), serviceTypeList, 30, TimeUnit.DAYS);

        return serviceTypeList;
    }
}
